﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ENG.TeachersDiary.Model;

namespace ENG.TeachersDiary
{
  public partial class FrmInsertMark : Form
  {

    DiaryDB db;
    Class currentClass;
    Subject currentSubject;
    List<int> changedStudentsID;

    public FrmInsertMark()
    {
      InitializeComponent();

      ReDB();
    }

    public void ReDB()
    {
      db = Common.DBConn;

      currentClass = Common.GetCurrentClass(db);
      currentSubject = Common.GetCurrentSubject(db);

      studentBindingSource.DataSource = db.Students.Where(
        i => i.ClassID == currentClass.ClassID);
      markGroupBindingSource.DataSource = db.MarkGroups.Where(
        i => i.SubjectID == currentSubject.SubjectID);
    }

    private void btnStorno_Click(object sender, EventArgs e)
    {
      changedStudentsID = null;

      this.Close();
    }

    private void btnSave_Click(object sender, EventArgs e)
    {
      if (mlbA.SelectedValue != null)
        InsertMarkToDB(mlbA.SelectedValue, txtA.Text);
      if (mlbB.SelectedValue != null)
        InsertMarkToDB(mlbB.SelectedValue, txtB.Text);
      if (mlbC.SelectedValue != null)
        InsertMarkToDB(mlbC.SelectedValue, txtC.Text);
      if (mlbD.SelectedValue != null)
        InsertMarkToDB(mlbD.SelectedValue, txtD.Text);

      db.SubmitChanges();

      changedStudentsID = new List<int>();
      changedStudentsID.Add(
        (cmbStudent.SelectedItem as Model.Student).StudentID);

      this.Close();
    }

    private void InsertMarkToDB(Model.MarkCode markCode, string noteText)
    {
      Model.Mark m = new Model.Mark();

      m.Date = dtpDate.Value;
      m.MarkGroupID = (lstMarkGroup.SelectedItem as Model.MarkGroup).MarkGroupID;
      m.MarkCodeID = markCode.MarkCodeID;
      m.StudentID = (cmbStudent.SelectedItem as Model.Student).StudentID;
      m.Note = noteText;

      db.Marks.InsertOnSubmit(m);
    }

    internal void Init(int? studentID, int? markGroupID)
    {
      if (studentID.HasValue) { 
      Model.Student s = db.Students.First(i => i.StudentID == studentID.Value);
      cmbStudent.SelectedItem = s;
      }

      if (markGroupID.HasValue)
      {
      Model.MarkGroup m = db.MarkGroups.First(i => i.MarkGroupID == markGroupID.Value);
      lstMarkGroup.SelectedItem = m;
      }
    }

    internal List<int> GetChangedStudentIDs()
    {
      return this.changedStudentsID;
    }
  }
}
